<template>
  <div class="vc-table no-empty-block">
    <el-table
      ref="filesTable"
      :data="filesTableData"
      size="small"
      style="width: 100%"
      tooltip-effect="light"
      @cell-mouse-enter="hoverOn"
      @cell-mouse-leave="hoverLeave"
      empty-text=" "
      stripe
    >
      <el-table-column
        label="序号"
        type='index'
        align="center"
        width="50">
      </el-table-column>
      <el-table-column label="文件名" align="left" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <a
            class="color-primary"
            style="cursor:pointer;text-decoration:none;line-height:30px;font-size:13px;"
            :href="scope.row.fileId ? `${uploadCfg.url}/dl/${scope.row.fileId}` : 'javascript:;'"
            @click="downloadFile(scope.row)"
          >{{ scope.row.fileName }}</a>
          <a
            v-if="scope.row.fileName"
            style="cursor: pointer;"
            @click="handleDeleteFile(scope.row)"
            v-show="scope.row.displayDeleteRow"
          ><i class="el-icon-close" style="color:red !important;font-weight:bold;"></i></a>
        </template>
      </el-table-column>
      <el-table-column label="进度" align="left" width="240px">
        <template slot-scope="scope">
          <el-progress v-if="scope.row.progressFlag==1" :percentage="scope.row.percent" style="margin-top:9px;"></el-progress>
          <div v-if="scope.row.progressFlag==2">上传成功</div>
          <div v-if="scope.row.progressFlag==3">
            <a
              style="color:red !important;cursor: pointer; "
              @click="uploadFileAgain(scope.row)"
            >上传失败，重新上传</a>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <tr class="el-table__row" style="height:39px" v-if="limit">
      <td
        rowspan="1"
        colspan="1"
        class="el-table_6_column_28 is-left"
        style="height:39px;line-height:39px"
      >
        <div class="cell">
          <el-upload
            :action="`${uploadCfg.url}/upload`"
            method="post"
            ref="upload_ref"
            multiple
            name="file"
            :show-file-list="false"
            :limit="limit"
            :on-exceed="handleExceed"
            :on-change="addRow"
            :auto-upload="true"
            enctype="multipart/form-data"
            :http-request="uploadFile"
            :before-upload="beforeUpload"
            :on-success="uploadSuccess"
            :on-error="uploadError"
            :on-remove="handleRemove"
            :file-list="fileList"
          >
            <el-button
              type="text"
              size="small"
              style="padding-left: 9px"
            >添加附件</el-button>
          </el-upload>
        </div>
      </td>
    </tr>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: 'uploadFile',
  props: {
    fileData: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  data () {
    return {
      displayDeleteRow: false,
      filesTableData: [],
      fileList: [],
      loading: false,
      uploadData: {
        appId: this.$store.state.config.data['wjfwyyid'],
        timestamp: '',
        sig: ''
      },
      limit: 10
    }
  },
  computed: {
    uploadCfg () {
      return {
        url: this.$store.state.config.data['wjfwqdz'] + '/yfs',
        secret: this.$store.state.config.data['wjfwyymy']
      }
    }
  },
  created () {
    this.findFileListById() // 根据id查询附件数据
  },
  watch: {
    fileData: {
      handler () {
        this.findFileListById()
      },
      deep: true
    },
    filesTableData: {
      handler (val) {
        this.limit = 10 - val.length
      },
      deep: true
    }
  },
  methods: {
    findFileListById () {
      this.filesTableData = this.fileData.map(item => {
        return {
          fileId: item.attmtId,
          fileName: item.attmtName,
          fileSize: item.attmtSize,
          progressFlag: 2
        }
      })
    },
    hoverOn (row) {
      if (row.name == null) {
        this.$set(row, 'displayDeleteRow', true)
      }
    },
    hoverLeave (row) {
      row.displayDeleteRow = false
    },
    /**
     * 上传文件之前的钩子
     */
    beforeUpload (file) {
      // if('application/zip' != file.type){
      //   this.$notifyBox("上传的文件只允许zip类型");
      //   return false;
      // }
      if (this.filesTableData.length > 0) {
        var index = this.filesTableData.findIndex(
          item => item.fileName === file.name
        )
        if (index >= 0) {
          this.$notifyBox('存在同名文件，已过滤！')
          return false
        }
      }
      const fileNameLimited = this.fileNameLenIsLimited(
        file.name.length
      )
      if (!fileNameLimited) {
        this.$notifyBox(this.GLOBAL.MSG.FILE_NAME_EXCEED_LENGTH, 'warning')
        return false
      }
      const limited = this.fileSizeIsLimited(file.size)
      if (!limited) {
        this.$notifyBox(this.GLOBAL.MSG.FILE_EXCEED_SIZE, 'warning')
        return false
      }
      let fileObj = {}
      fileObj.fileName = file.name
      fileObj.percent = 0
      fileObj.progressFlag = 0
      this.filesTableData.push(fileObj)
      this.$nextTick(() => {
        this.$refs.filesTable.bodyWrapper.scrollTop = this.$refs.filesTable.bodyWrapper.scrollHeight + 45
      })

      this.loading = true
      let sha256 = require('js-sha256').sha256
      this.uploadData.timestamp = Date.now()
      this.uploadData.sig = sha256(
        this.uploadData.appId +
          this.uploadCfg.secret +
          this.uploadData.timestamp
      )
    },
    /**
     * 文件上传成功时的钩子
     */
    uploadSuccess (response, file) {
      if (!response.success) {
        this.handleCatch(response, this.GLOBAL.MSG.UPLOAD_ERR_MSG)
      }
    },
    /**
     * 文件上传失败时的钩子
     */
    uploadError (err) {
      this.handleCatch(err, this.GLOBAL.MSG.UPLOAD_ERR_MSG)
    },
    /**
     * 捕获异常处理
     */
    handleCatch (err, msg = '') {
      this.loading = false
      this.$notifyBox(msg, 'error')
      window.console && console.log(err)
    },
    /**
     * 超出文件上传数量的钩子
     */
    handleExceed (files) {
      this.$notifyBox('最多只能上传10个文件')
    },
    /**
     * 添加一行附件
     */
    addRow (fileObj, fileList) {
      // console.log(fileObj, fileList);
    },
    /** 上传文件 */
    uploadFile (param) {
      let index = this.filesTableData.findIndex(
        item => item.fileName === param.file.name
      )
      var fileObj = this.filesTableData[index]
      fileObj.fileName = param.file.name
      fileObj.file = param.file
      fileObj.percent = 0
      fileObj.progressFlag = 1
      var length = param.file.size
      fileObj.fileSize = Math.round(length / 1024)
      this.uploadFileCommon(fileObj)
    },
    /** 重新上传 */
    uploadFileAgain (fileObj) {
      fileObj.progressFlag = 1
      this.uploadFileCommon(fileObj)
    },
    /** 上传文件 */
    uploadFileCommon (fileObj) {
      var form = new FormData()
      form.append('file', fileObj.file)
      form.append('appId', this.uploadData.appId)
      form.append('timestamp', this.uploadData.timestamp)
      form.append('sig', this.uploadData.sig)
      const that = this
      axios
        .post(this.uploadCfg.url + '/upload', form, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: progressEvent => {
            let percent =
              ((progressEvent.loaded / progressEvent.total) * 100) | 0
            XMLHttpRequestEventTarget // 调用onProgress方法来显示进度条，需要传递个对象 percent为进度值
            fileObj.percent = percent
            that.$forceUpdate()
          }
        })
        .then(res => {
          if (this.$refs.upload_ref) {
            this.$refs.upload_ref.clearFiles()
          }
          // 已被删除
          if (fileObj.fileName == null || fileObj.fileName == '') {
            fileObj.percent = 0
            fileObj.fileName = null
            fileObj.progressFlag = 0
            that.$forceUpdate()
            return
          }
          // 上传失败
          if (res.data.success == false) {
            fileObj.percent = 0
            // fileObj.fileName = null;
            fileObj.progressFlag = 3
            that.$forceUpdate()
            this.$notifyBox(
              fileObj.fileName + '上传失败，请重新上传',
              'warning'
            )
            return
          }
          // 上传成功
          fileObj.progressFlag = 2
          fileObj.fileId = res.data.data
          that.$forceUpdate()
        })
        .catch(err => {
          fileObj.percent = 0
          // fileObj.fileName = null;
          fileObj.progressFlag = 3
          that.$forceUpdate()
          this.$notifyBox(fileObj.fileName + '上传失败，请重新上传', 'warning')
        })
    },
    /**
     * 删除文件时的钩子
     */
    handleRemove (file, fileList) {},
    /**
     * 删除文件
     */
    handleDeleteFile (row) {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.filesTableData.splice(
            this.filesTableData.findIndex(item => item.fileId === row.fileId),
            1
          )
        })
        .catch(() => {})
    },
    /**
     * 删除整行
     */
    handleDeleteRow (row) {
      // this.$confirmBox(this.deleteRow(row));
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: type
      })
        .then(() => {
          this.filesTableData.splice(
            this.filesTableData.findIndex(item => item.fileId === row.fileId),
            1
          )
        })
        .catch(() => {})
    },
    /**
     * 下载未上传完成的文件时给出提示
     */
    downloadFile (row) {
      !row.fileId && this.$notifyBox('文件未上传完成，请等待', 'warning')
    },
    /**
     * 判断文件名长度是否超出限制
     */
    fileNameLenIsLimited (size, limit = 40) {
      return size <= limit
    },
    /**
     * 判断上传文件大小是否超出限制500M
     */
    fileSizeIsLimited (size, limit = 200) {
      return size / 1024 / 1024 <= limit
    }
  }
}
</script>
